//
//  personCenterViewController.m
//  BeautyPicture
//
//  Created by 沈振邦 on 15/8/11.
//  Copyright (c) 2015年 szb. All rights reserved.
//

#import "personInfoViewController.h"
#import "PCLabelItem.h"
#import "PersonCenterGroup.h"
#import "PCArrowItm.h"
#import "PersonCenterCellView.h"
#import "VPImageCropperViewController.h"
#import "changeName.h"
#import "HZAreaPickerView.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "BPhttpTool.h"
#import "AccountTool.h"
#import "QiniuSDK.h"
#import "MBProgressHUD+MJ.h"
#import "BPImageTool.h"
#import "changeNewPhoneVC.h"
#import "BPLoginViewController.h"
#import "AppDelegate.h"

#define ORIGINAL_MAX_WIDTH 640.0f

@interface personInfoViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate,VPImageCropperDelegate,HZAreaPickerDelegate>

@property (strong, nonatomic) HZAreaPickerView *locatePicker;

@end

@implementation personInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpBaseData];
    
    [self setUpTableView];
    
    [self setUpHideView];
    
    [self setUpDatePicker];
}

- (void)setUpBaseData
{
    _accountInfo = [AccountTool account];
    
    _person = [[PersonalCenterVC alloc] init];
}

- (void)setUpHideView
{
    self.title = @"个人信息";
    _hideTapView = [[UIView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:_hideTapView];
    _hideTapView.hidden = YES;
    UITapGestureRecognizer *hideTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideView)];
    [_hideTapView addGestureRecognizer:hideTap];
}

- (UIView *)headView
{
    if (_headView == nil) {
        CGFloat headH = 96.0f;
        _headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, BPScreenW, headH)];
        
        UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(BPStatusCellInset + 5.0, 0, 60, headH)];
        textLabel.text = @"头像";
        textLabel.textAlignment = NSTextAlignmentLeft;
        [_headView addSubview:textLabel];
        
        CGFloat imageW = _headView.height - 7.0 * 2.0;
        CGFloat imageX = _headView.width - BPStatusCellInset - imageW - 3.0;
        
        UIView *avatarView = [[UIView alloc] initWithFrame:CGRectMake(imageX - 2.0, 7.0 - 2.0, imageW + 4.0, imageW + 4.0)];
        avatarView.backgroundColor = [UIColor whiteColor];
        [avatarView.layer setMasksToBounds:YES];
        [avatarView.layer setCornerRadius:41.0f];
        [_headView addSubview:avatarView];
        
        _avatarImage = [[UIImageView alloc] initWithFrame:CGRectMake(imageX, 7.0, imageW, imageW)];
        _avatarImage.backgroundColor = [UIColor grayColor];
        if (_accountInfo.imageData == nil) {
            if(_accountInfo.face != nil){
                [BPImageTool setUpUIImageView:_avatarImage addNsstringUrl:_accountInfo.face];
                _accountInfo.imageData = UIImageJPEGRepresentation(_avatarImage.image, 1.0);
                [AccountTool save:_accountInfo];
            }

        }else{
        _avatarImage.image = [UIImage imageWithData:_accountInfo.imageData];
        }
        
        [_avatarImage.layer setMasksToBounds:YES];
        [_avatarImage.layer setCornerRadius:40.0f];
        [_headView addSubview:_avatarImage];
        
        UITapGestureRecognizer *changeIcon = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeIcon)];
        [_headView addGestureRecognizer:changeIcon];
    }
    return _headView;
}

- (void)setUpDatePicker
{
    _TimePicker = [[UIDatePicker alloc] init];
    _TimePicker.datePickerMode = UIDatePickerModeDate;
    _TimePicker.minuteInterval = 1;
    _TimePicker.backgroundColor = [UIColor whiteColor];
    [_TimePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
    
    _TimePicker.frame = CGRectMake(0, BPScreenH, BPScreenW, 200.0);
    
    [self.view addSubview:_TimePicker];
}

- (void)setUpTableView
{
    self.tableView.tableHeaderView = self.headView;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [self setUpGroups];
}

- (void)setUpGroups
{
    PersonCenterGroup *group = [PersonCenterGroup group];
    
    [self.groups addObject:group];
    
    //换昵称
    PCLabelItem *AllIndent = [PCLabelItem itewWithTitle:@"我的昵称"];
    AllIndent.text = _accountInfo.nickname;
    __block PCLabelItem *itemOneBlock=AllIndent;
    AllIndent.operation = ^{
        changeName *change = [[changeName alloc] init];
        change.beforeName = itemOneBlock.text;
        change.block=^(NSString *name){
            itemOneBlock.text = name;
            [self.tableView reloadData];
            //保存在本地
            _accountInfo.nickname = name;
            [AccountTool save:_accountInfo];
            //上传服务器
            NSMutableDictionary *param = [NSMutableDictionary dictionary];
            [param setValue:@"nickname" forKey:@"field"];
            [param setValue:name forKey:@"value"];
            [self httpPostChangeInfo:param];
        };
        
        [self.navigationController pushViewController:change animated:YES];
    };
    
    //换性别
    PersonInfo = [PCLabelItem itewWithTitle:@"性别"];
    __weak personInfoViewController *test = self;
    PersonInfo.operation = ^{
        [test changeSex];
        
    };
    if (_accountInfo.sex  == 0) {
        PersonInfo.text = @"";
    }else if ([_accountInfo.sex intValue] == 1){
        PersonInfo.text = @"男";
    }else
    {
        PersonInfo.text = @"女";
    }
    
    //换手机
    PCLabelItem *RequestCode = [PCLabelItem itewWithTitle:@"绑定手机"];
    RequestCode.text = _accountInfo.mobile;
    __block PCLabelItem *itemOneBlock2=RequestCode;
    RequestCode.operation = ^{
        changeNewPhoneVC *change = [[changeNewPhoneVC alloc] init];
        change.block=^(NSString *newPhone){
            itemOneBlock2.text = newPhone;
            [self.tableView reloadData];
            //保存在本地
            _accountInfo.mobile = newPhone;
            [AccountTool save:_accountInfo];
            
            //上传服务器
            NSMutableDictionary *param = [NSMutableDictionary dictionary];
            [param setValue:@"mobile" forKey:@"field"];
            [param setValue:newPhone forKey:@"value"];
            [self httpPostChangeInfo:param];
        };
        [self.navigationController pushViewController:change animated:YES];
    };
    
    //换地区
    _Saddress = [PCLabelItem itewWithTitle:@"地区"];
    _Saddress.text = _accountInfo.area;
    __weak typeof(self) weakSelf = self;
    _Saddress.operation = ^{
        [weakSelf cancelLocatePicker];
        weakSelf.locatePicker = [[HZAreaPickerView alloc] initWithStyle:HZAreaPickerWithStateAndCity delegate:weakSelf];
        [weakSelf.locatePicker showInView:weakSelf.view];
        weakSelf.hideTapView.hidden = NO;
    };
   
    //换生日
    PCLabelItem *Voucher = [PCLabelItem itewWithTitle:@"生日"];
    Voucher.text = _accountInfo.birthday;
    Voucher.operation=^{
        [weakSelf buttomTableViewappear:_TimePicker];
    };
    _Voucher = Voucher;
    
    //添加组
    group.items = @[AllIndent,PersonInfo,RequestCode,_Saddress,Voucher];
}

- (void)changeSex
{
    UIActionSheet *sexSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"男", @"女", nil];
    sexSheet.tag = 101;
    [sexSheet showInView:self.view];
}

//换头像
- (void)changeIcon
{
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"拍照", @"从相册中选取", nil];
    choiceSheet.tag = 100;
    [choiceSheet showInView:self.view];
}

- (void)httpPostChangeInfo:(NSMutableDictionary *)dicInfo
{
    [dicInfo setValue:_accountInfo.uid forKey:@"uid"];
    [BPhttpTool post:[NSString stringWithFormat:@"%@user/updateInfo",BPhttp] params:dicInfo success:^(id responseObj) {
    } failure:^(NSError *error) {
        
    }];
}

#pragma mark VPImageCropperDelegate
- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    _avatarImage.image = editedImage;
    //保存数据在本地
    _accountInfo.imageData = UIImageJPEGRepresentation(editedImage, 0.4);
    [AccountTool save:_accountInfo];
    //1.获取token，上传七牛
    NSString *url = [NSString stringWithFormat:@"%@Upload/get_qiniu_token",BPhttp];
    [BPhttpTool get:url params:nil success:^(id responseObj) {
        NSString *token = [responseObj valueForKey:@"token"];
        QNUploadManager *upManger = [[QNUploadManager alloc] init];
        NSData *imageData = UIImageJPEGRepresentation(editedImage, 0.4);
        [upManger putData:imageData key:nil token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
            NSString *faceKey = resp[@"key"];
            NSMutableDictionary *param = [NSMutableDictionary dictionary];
            [param setValue:faceKey forKey:@"face"];
            [param setValue:_accountInfo.uid forKey:@"uid"];
            [BPhttpTool post:[NSString stringWithFormat:@"%@user/saveface",BPhttp] params:param success:^(id responseObj) {
                NSDictionary *dic = responseObj;
                if ([dic[@"status"] intValue] == 1) {
                    [MBProgressHUD showSuccess:@"换头像成功"];
                }
                
            } failure:^(NSError *error) {
                BPLog(@"头像上传失败");
            }];
        } option:nil];
        
    } failure:^(NSError *error) {
        BPLog(@"获取token失败");
    }];
    
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
        // TO DO
    }];
}

- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
    }];
}

#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (actionSheet.tag == 100) {
        if (buttonIndex == 0) {
            // 拍照
            if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
                UIImagePickerController *controller = [[UIImagePickerController alloc] init];
                controller.sourceType = UIImagePickerControllerSourceTypeCamera;
                if ([self isFrontCameraAvailable]) {
                    controller.cameraDevice = UIImagePickerControllerCameraDeviceFront;
                }
                NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
                [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
                controller.mediaTypes = mediaTypes;
                controller.delegate = self;
                [self presentViewController:controller
                                   animated:YES
                                 completion:^(void){
                                     NSLog(@"Picker View Controller is presented");
                                 }];
            }
            
        } else if (buttonIndex == 1) {
            // 从相册中选取
            if ([self isPhotoLibraryAvailable]) {
                UIImagePickerController *controller = [[UIImagePickerController alloc] init];
                controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
                [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
                controller.mediaTypes = mediaTypes;
                controller.delegate = self;
                [self presentViewController:controller
                                   animated:YES
                                 completion:^(void){
                                     NSLog(@"Picker View Controller is presented");
                                 }];
            }
        }
    }else{
        if (buttonIndex == 0) {
            PersonInfo.text = @"男";
            _accountInfo.sex = [NSString stringWithFormat:@"1"];
            
            NSMutableDictionary *param = [NSMutableDictionary dictionary];
            [param setValue:@"sex" forKey:@"field"];
            [param setValue:@"1" forKey:@"value"];
            [self httpPostChangeInfo:param];
            
        } else if (buttonIndex == 1) {
            PersonInfo.text = @"女";
            _accountInfo.sex = [NSString stringWithFormat:@"2"];
            
            NSMutableDictionary *param = [NSMutableDictionary dictionary];
            [param setValue:@"sex" forKey:@"field"];
            [param setValue:@"2" forKey:@"value"];
            [self httpPostChangeInfo:param];
        }
        [AccountTool save:_accountInfo];
        [self.tableView reloadData];
        
        
    }
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^() {
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        portraitImg = [self imageByScalingToMaxSize:portraitImg];
        // 裁剪
        VPImageCropperViewController *imgEditorVC = [[VPImageCropperViewController alloc] initWithImage:portraitImg cropFrame:CGRectMake(0, 100.0f, self.view.frame.size.width, self.view.frame.size.width) limitScaleRatio:3.0];
        imgEditorVC.delegate = self;
        [self presentViewController:imgEditorVC animated:YES completion:^{
            // TO DO
        }];
    }];
}

//换地区
-(void)pickerDidChaneStatus:(HZAreaPickerView *)picker
{
    _Saddress.text = [NSString stringWithFormat:@"%@ %@", picker.locate.state, picker.locate.city];
    [self.tableView reloadData];
    [self cancelLocatePicker];
    
    //保存在本地
    _accountInfo.area = _Saddress.text;
    [AccountTool save:_accountInfo];
    //上传服务器
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:@"area" forKey:@"field"];
    [param setValue:_Saddress.text forKey:@"value"];
    [self httpPostChangeInfo:param];
}

- (void)cancelAreaChoose:(HZAreaPickerView *)picker
{
    [self cancelLocatePicker];
}

//换生日
- (void)dateChanged:(UIDatePicker *)datePicker
{
    NSDate *_date = datePicker.date;
    NSDateFormatter *dateNow = [[NSDateFormatter alloc] init];
    [dateNow setDateFormat:@"yyyy-MM-dd"];
    NSString *dateStr = [dateNow stringFromDate:_date];
    _Voucher.text = dateStr;
    [self.tableView reloadData];
    
    //保存在本地
    _accountInfo.birthday = _Voucher.text;
    [AccountTool save:_accountInfo];
    //上传服务器
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:@"birthday" forKey:@"field"];
    [param setValue:_Voucher.text forKey:@"value"];
    [self httpPostChangeInfo:param];
}


-(void)cancelLocatePicker
{
    self.hideTapView.hidden = YES;
    [self.locatePicker cancelPicker];
    self.locatePicker.delegate = nil;
    self.locatePicker = nil;
}

- (void)buttomTableViewappear:(UIView *)view
{
    _hideTapView.hidden = NO;
    [UIView animateWithDuration:0.5 animations:^{
        view.y = view.y - view.height;
    }];
}

- (void)buttomTableViewDisappear
{
    _hideTapView.hidden = YES;
    [UIView animateWithDuration:0.3 animations:^{
        _TimePicker.y = BPScreenH;
    }];
}

- (void)hideView
{
    [self cancelLocatePicker];
    [self buttomTableViewDisappear];
}

#pragma mark camera utility
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isRearCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickVideosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickPhotosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}

- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < ORIGINAL_MAX_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = ORIGINAL_MAX_WIDTH;
        btWidth = sourceImage.size.width * (ORIGINAL_MAX_WIDTH / sourceImage.size.height);
    } else {
        btWidth = ORIGINAL_MAX_WIDTH;
        btHeight = sourceImage.size.height * (ORIGINAL_MAX_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
